package tsou.com.simple.realmtest.migration;

import io.realm.DynamicRealm;
import io.realm.DynamicRealmObject;
import io.realm.RealmMigration;
import io.realm.RealmObjectSchema;
import io.realm.RealmSchema;

/**
 * Created by Administrator on 2017/12/19 0019.
 * 数据迁移
 */

public class CustomMigration implements RealmMigration {
    @Override
    public void migrate(final DynamicRealm realm, long oldVersion, long newVersion) {
        RealmSchema schema = realm.getSchema();
        if (oldVersion == 0 && newVersion == 1) {
            schema.get("MigrationPerson")
                    .removePrimaryKey()//去除主键标志
                    .removeField("sex")//删除sex字段
                    .renameField("age", "myage")//更改age字段为myage字段
                    .addField("num", int.class)//添加num字段int类型
                    .addField("project", String.class)//添加project字段int类型，
//                    .addField("id", long.class, FieldAttribute.PRIMARY_KEY)//使用三个参数的,可设置注释属性
                    .addRealmObjectField("men", schema.get("Men"))//添加对象
                    .addRealmListField("mens", schema.get("Men"))//添加集合对象
                    .transform(new RealmObjectSchema.Function() {
                        @Override
                        public void apply(DynamicRealmObject obj) {
                            DynamicRealmObject men = realm.createObject("Men");
                            men.set("name", "迁移Men");
                            men.set("age", 8);
                            obj.setObject("men", men);//初始化值的操作
                            obj.getList("mens").add(men);
                        }
                    });
            oldVersion++;
        }
    }
}
